package util

import (
	"bytes"
	"runtime"
	"strconv"
)

//v,mixSeed must between [0, 1.0]
func MixRand(v, mixSeed float32) float32 {
	v = v - mixSeed
	if v < 0 {
		v = v + 1.0
	}
	return v
}

var autoMixSeed float32 = 0.398459734573

//return a mixed float32 by another random number, mixed by v.
//return value between [0, 1.0]
func MixRandAuto(v float32) float32 {
	var mixSeed float32 = autoMixSeed
	v = v - mixSeed
	if v < 0 {
		v = v + 1.0
	}
	autoMixSeed += 0.01377829189234
	if autoMixSeed > 1.0 {
		autoMixSeed -= 0.9999
	}
	return v
}

func GetGoroutineID() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}

var randF float32 = 0

//rate in [0,1.0]
func InAvgRate(idx int, rate float32) bool {
	randF += 1.0 / rate
	a := int(1.0 / rate)
	if ((idx) % a) <= 1 {
		return true
	}
	return false
}
